package com.legendshop.code.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.legendshop.code.config.Config;

public class Log {
    public static final int LEVEL_DEBUG = 0;
    public static final int LEVEL_INFO = 1;
    public static final int LEVEL_ERROR = 2;
    private static Timestamp time = new Timestamp(System.currentTimeMillis());
    private static StringBuffer infoBuffer = new StringBuffer(200);

    public Log() {
    }

    public static void log(int i, int level) {
        log("" + i, level);
    }

    public static void log(String info, int level) {
        if (level >= Config.getInstance().getLogLevel()) {
            logf(info, level);
        }
    }

    public static void log(String info) {
        log(info, 0);
    }

    public static void log(int info) {
        log(info, 0);
    }

    private static synchronized void logf(String info, int level) {
        infoBuffer.delete(0, infoBuffer.length());
        time.setTime(System.currentTimeMillis());
        infoBuffer.append("[").append(level).append("]").append(time.toString()).append("\t").append(info);
        writeFile(infoBuffer.toString());
    }

    public static void log(Exception e) {
        log(e.getMessage(), 2);
        if (Config.getInstance().getLogLevel() <= 2) {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(Config.getInstance().getPath() + "log" + File.separator + "log.txt", true);
                e.printStackTrace(new PrintStream(fos));
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (Exception es) {
                        es.printStackTrace();
                    }
                }
            }
        }
    }

    private static void writeFile(String message) {
        String Path = Config.getInstance().getPath() + File.separator + "log";
        createDictory(Path);
        String filePath = Config.getInstance().getPath() + File.separator + "log" + File.separator + "log.txt";
        File f = new File(filePath);
        if (f.exists()) {
            writeFile(message, filePath);
        } else {
            writeFile(message, filePath, false);
        }
    }

    public static void writeFile(String message, String path) {
        writeFile(message, path, true);
    }

    public static void writeFile_Old2(String message, String path, boolean append) {
        File outFile = new File(path);
        FileWriter outFileWriter = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            outFileWriter = new FileWriter(outFile);
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(outFile, append), "UTF-8");
            outputStreamWriter.write(message + System.getProperty("line.separator"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStreamWriter.close();
                //outFileWriter.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void writeFile(String message, String path, boolean append) {
        OutputStreamWriter outputStreamWriter = null;
        try {
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(path, append), "UTF-8");
            outputStreamWriter.write(message + System.getProperty("line.separator"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStreamWriter.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void writeFile_Old(String message, String path, boolean append) {
        FileWriter os = null;
        try {
            os = new FileWriter(path, append);
            os.write(message + System.getProperty("line.separator"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static List readFile(String filename) throws IOException {
        return readFile(filename, 0, 2147483647);
    }

    public static List readFile(String filename, int beginPos, int endPos) throws IOException {
        List list = new ArrayList(100);
        BufferedReader reader = null;
        String s = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(filename))));
            for (int pos = 0; ((s = reader.readLine()) != null) && (pos >= beginPos) && (pos++ < endPos);) {
                list.add(s);
            }

        } catch (IOException e) {
            log(e);
            throw e;
        }
        return list;
    }

    public static void createDictory(String path) {
        File f = new File(path);
        File ft = f;
        for (; !f.exists(); f = f.getParentFile()) {
            ft = f;
        }

        if (f != ft) {
            ft.mkdir();
            createDictory(path);
        }
    }

    public static void copyFile(String oldPathFile, String newPathFile) {
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            int byteread = 0;
            File oldfile = new File(oldPathFile);
            if (oldfile.exists()) {
                inStream = new FileInputStream(oldPathFile);
                fs = new FileOutputStream(newPathFile);
                byte buffer[] = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
            } catch (Exception ex) {
            }
            try {
                fs.close();
            } catch (Exception ex) {
            }
        }
    }

    public static String writeFile(String fileContent, String parentFilePath, String uploadedFileName,
            boolean nameChanged, boolean overwrited, boolean formatText) {

        try {

            File parentPath = new File(parentFilePath);
            if (!parentPath.exists()) {
                parentPath.mkdirs();
            }

            File outFile = new File(parentFilePath + File.separator + uploadedFileName);
            if (outFile.exists() && nameChanged) {
                uploadedFileName = UID.getUID() + "_" + uploadedFileName;
                outFile = new File(parentFilePath + File.separator + uploadedFileName);
            } else if (outFile.exists() && !overwrited) {
                return uploadedFileName;
            }

            FileWriter outFileWriter = new FileWriter(outFile);
            // BufferedWriter outBufferedReader = new
            // BufferedWriter(outFileWriter);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(outFile), "GBK");
            StringBuffer formatSb = new StringBuffer();
            if (formatText) {
                formatSb.append(" <P> ");
                for (int i = 0; i < fileContent.length(); i++) {
                    if (new String(new char[] { fileContent.charAt(i) }).equals(" ")) {
                        formatSb.append(" &nbsp;&nbsp; ");
                    } else if (new String(new char[] { fileContent.charAt(i) }).equals("\n")) {
                        formatSb.append(" <br> ");
                    } else if (new String(new char[] { fileContent.charAt(i) }).equals("\n")
                            && new String(new char[] { fileContent.charAt(i + 1) }).equals("\n")
                            && ((i + 1) != fileContent.length())) {
                        formatSb.append(" </P><br><P> ");
                        i++;
                    } else {
                        formatSb.append(new String(new char[] { fileContent.charAt(i) }));
                    }
                }
                formatSb.append("</P>");
                fileContent = formatSb.toString();
            }

            outputStreamWriter.write(fileContent);
            outputStreamWriter.close();
            outFileWriter.close();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return uploadedFileName;
    }

}